package com.tt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tt.reggie.common.BaseContext;
import com.tt.reggie.common.R;
import com.tt.reggie.dto.SetmealDto;
import com.tt.reggie.entity.Category;
import com.tt.reggie.entity.Dish;
import com.tt.reggie.entity.Setmeal;
import com.tt.reggie.entity.SetmealDish;
import com.tt.reggie.service.CategoryService;
import com.tt.reggie.service.DishService;
import com.tt.reggie.service.SetmealDishService;
import com.tt.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.like(name!=null,Setmeal::getName,name);
        setmealService.page(pageInfo,setmealLambdaQueryWrapper);

        //重新构造分页构造器
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");
        //获取页面信息
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> setmealDtoRecords = new ArrayList<>();

        for(Setmeal setmeal : records){
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            Category byId = categoryService.getById(setmeal.getCategoryId());
            setmealDto.setCategoryName(byId.getName());
            setmealDtoRecords.add(setmealDto);
        }
        setmealDtoPage.setRecords(setmealDtoRecords);

        return R.success(setmealDtoPage);
    }


    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> saveSetMeal(@RequestBody SetmealDto setmealDto, HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);
        log.info(setmealDto.toString());

        setmealService.save(setmealDto);
        Long setMealId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes){
            setmealDish.setSetmealId(setMealId);
        }
        setmealDishService.saveBatch(setmealDishes);

        return R.success("增加成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateById(@PathVariable int status,@RequestParam List<Long> ids,HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        //若要启售套餐，需要判断其中菜品是否启售
        if(status==1){
            //查询套餐中所有的菜品id
            List<Long> idList = new ArrayList<>();

            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);

            List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
            for(SetmealDish setmealDish : list){
                idList.add(setmealDish.getDishId());
            }
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getStatus,0);
            dishLambdaQueryWrapper.in(Dish::getId,idList);
            int count = dishService.count(dishLambdaQueryWrapper);
            if(count>0){
                return R.error("套餐内的菜品需要启售才能启售套餐！");
            }
        }

        List<Setmeal> setmealList = new ArrayList<>();
        for(Long id : ids){
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(status);
            setmeal.setId(id);
            setmealList.add(setmeal);
        }
        setmealService.updateBatchById(setmealList);
        return R.success("更改成功！");
    }

    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> deleteById(@RequestParam List<Long> ids){
        //判断要删除的套餐是否启售
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        int count = setmealService.count(setmealLambdaQueryWrapper);
        if(count>0){
            return R.error("启售的套餐不能删除，先将要删除的套餐停售");
        }

        setmealService.removeByIds(ids);

        return R.success("删除成功！");
    }


    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        SetmealDto setmealDto = new SetmealDto();
        Setmeal byId = setmealService.getById(id);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(lambdaQueryWrapper);
        BeanUtils.copyProperties(byId,setmealDto);
        setmealDto.setSetmealDishes(list);

        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto,HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        //更改套餐信息
        setmealService.updateById(setmealDto);

        //更改套餐中的菜品信息
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(setmealDishLambdaQueryWrapper);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);


        return R.success("修改成功！");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public R<List<SetmealDto>> listR(Long categoryId,Integer status){
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getCategoryId,categoryId).eq(Setmeal::getStatus,status);
        List<Setmeal> list = setmealService.list(wrapper);
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal setmeal : list){
            Long setmealId = setmeal.getId();
                LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId,setmealId);
            List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            setmealDto.setSetmealDishes(setmealDishes);
            setmealDtoList.add(setmealDto);
        }
        return R.success(setmealDtoList);
    }




}
